﻿using System;
using System.Windows.Navigation;
using System.Windows.Threading;
using WebFlipScreenSaver.Model;
using mshtml;
using UserControl = System.Windows.Controls.UserControl;

namespace WebFlipScreenSaver.View
{
	/// <summary>
	/// Interaction logic for WebPageView.xaml
	/// </summary>
	public partial class WebPageView : UserControl
	{
		private int _loginAttempts = 0;
		DispatcherTimer _timer= new DispatcherTimer();
		public WebPageView()
		{
			InitializeComponent();

			browser.WebBrowser().LoadCompleted += WebPageView_LoadCompleted;
		}


		void WebPageView_LoadCompleted(object sender, NavigationEventArgs e)
		{

			if (_loginAttempts == 0)
				LoginWebPage((DataContext as WebPageViewModel).WebConfig, null);
		}


		public  void LoginWebPage(WebPageConfigurationViewModel webPageConfigurationViewModel, WebPageView webPageView)
		{

			var doc = browser.WebBrowser().Document as HTMLDocument;
			if(webPageConfigurationViewModel.RequiresAuth)
			{
					
				var username = doc.getElementById(webPageConfigurationViewModel.UsernameElementName);
				if(username != null)
					username.setAttribute("value", webPageConfigurationViewModel.SiteUserName);

				var password = doc.getElementById(webPageConfigurationViewModel.PasswordElementName);
				if(password != null)
				{
					password.setAttribute("value", webPageConfigurationViewModel.SitePassword);
					if (doc.forms != null && doc.forms.length > 0)
					{
						var form = doc.forms.item(0) as HTMLFormElement;
						if(form != null)
						{
							_loginAttempts++;
							form.submit();
						}
						
					}
				}

			}
		}



	}
}
